// API服务入口文件
// 统一导出所有API服务和工具

// 核心API客户端
export * from './ApiClient';

// 具体API服务
export * from './FileSystemApi';
export * from './CodeGraphApi';
export * from './LspApi';

// 重新导出主要实例
export { apiClient } from './ApiClient';
export { fileSystemApi } from './FileSystemApi';
export { codeGraphApi } from './CodeGraphApi';
export { lspApi } from './LspApi';

// API服务管理器
class ApiServiceManager {
  private initialized = false;
  private services = new Map<string, any>();

  // 初始化所有API服务
  async initialize(): Promise<void> {
    if (this.initialized) return;

    console.log('🔌 Initializing API services...');

    try {
      // 注册服务
      this.services.set('filesystem', fileSystemApi);
      this.services.set('codegraph', codeGraphApi);
      this.services.set('lsp', lspApi);

      // 设置全局错误处理
      this.setupGlobalErrorHandling();

      // 设置性能监控
      this.setupPerformanceMonitoring();

      this.initialized = true;
      console.log('✅ API services initialized successfully');
    } catch (error) {
      console.error('❌ Failed to initialize API services:', error);
      throw error;
    }
  }

  // 获取服务
  getService<T = any>(name: string): T | undefined {
    return this.services.get(name);
  }

  // 检查服务健康状态
  async healthCheck(): Promise<{
    overall: 'healthy' | 'degraded' | 'unhealthy';
    services: Record<string, {
      status: 'healthy' | 'unhealthy';
      latency?: number;
      error?: string;
    }>;
  }> {
    const results: Record<string, any> = {};
    let healthyCount = 0;

    for (const [name, service] of this.services) {
      try {
        const start = performance.now();
        
        // 执行健康检查（这里可以调用具体的健康检查方法）
        // 暂时使用简单的检查
        if (service && typeof service === 'object') {
          results[name] = {
            status: 'healthy',
            latency: performance.now() - start,
          };
          healthyCount++;
        } else {
          results[name] = {
            status: 'unhealthy',
            error: 'Service not available',
          };
        }
      } catch (error) {
        results[name] = {
          status: 'unhealthy',
          error: error instanceof Error ? error.message : 'Unknown error',
        };
      }
    }

    const totalServices = this.services.size;
    const overall = healthyCount === totalServices 
      ? 'healthy' 
      : healthyCount > 0 
        ? 'degraded' 
        : 'unhealthy';

    return {
      overall,
      services: results,
    };
  }

  // 获取API统计信息
  getStats(): {
    totalServices: number;
    cacheStats: any;
    requestStats: any;
  } {
    return {
      totalServices: this.services.size,
      cacheStats: apiClient.getCacheStats(),
      requestStats: {
        // 这里可以添加请求统计信息
        pending: 0,
        completed: 0,
        failed: 0,
      },
    };
  }

  // 清理资源
  async cleanup(): Promise<void> {
    console.log('🧹 Cleaning up API services...');

    try {
      // 销毁API客户端
      apiClient.destroy();

      // 清理服务
      this.services.clear();

      this.initialized = false;
      console.log('✅ API services cleaned up successfully');
    } catch (error) {
      console.error('❌ Failed to cleanup API services:', error);
    }
  }

  // 设置全局错误处理
  private setupGlobalErrorHandling(): void {
    // 这里可以添加全局错误处理逻辑
    console.log('🛡️ Global error handling setup completed');
  }

  // 设置性能监控
  private setupPerformanceMonitoring(): void {
    // 这里可以添加性能监控逻辑
    console.log('📊 Performance monitoring setup completed');
  }
}

// 全局API服务管理器实例
export const apiServiceManager = new ApiServiceManager();

// API工具函数
export const apiUtils = {
  // 批量执行API调用
  async batch<T = any>(
    calls: Array<() => Promise<T>>
  ): Promise<Array<T | Error>> {
    const results = await Promise.allSettled(calls.map(call => call()));
    return results.map(result => 
      result.status === 'fulfilled' ? result.value : result.reason
    );
  },

  // 重试API调用
  async retry<T = any>(
    fn: () => Promise<T>,
    maxRetries: number = 3,
    delay: number = 1000
  ): Promise<T> {
    let lastError: Error;

    for (let i = 0; i <= maxRetries; i++) {
      try {
        return await fn();
      } catch (error) {
        lastError = error as Error;
        
        if (i < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
        }
      }
    }

    throw lastError!;
  },

  // 超时包装
  async timeout<T = any>(
    promise: Promise<T>,
    ms: number
  ): Promise<T> {
    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms);
    });

    return Promise.race([promise, timeoutPromise]);
  },

  // 防抖API调用
  debounce<T extends (...args: any[]) => Promise<any>>(
    fn: T,
    delay: number
  ): T {
    let timeoutId: NodeJS.Timeout;
    
    return ((...args: any[]) => {
      clearTimeout(timeoutId);
      return new Promise((resolve, reject) => {
        timeoutId = setTimeout(async () => {
          try {
            const result = await fn(...args);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        }, delay);
      });
    }) as T;
  },

  // 节流API调用
  throttle<T extends (...args: any[]) => Promise<any>>(
    fn: T,
    delay: number
  ): T {
    let lastCall = 0;
    let timeoutId: NodeJS.Timeout;
    
    return ((...args: any[]) => {
      const now = Date.now();
      
      if (now - lastCall >= delay) {
        lastCall = now;
        return fn(...args);
      } else {
        return new Promise((resolve, reject) => {
          clearTimeout(timeoutId);
          timeoutId = setTimeout(async () => {
            try {
              lastCall = Date.now();
              const result = await fn(...args);
              resolve(result);
            } catch (error) {
              reject(error);
            }
          }, delay - (now - lastCall));
        });
      }
    }) as T;
  },
};

// 开发工具
export const apiDevTools = {
  // 监控API调用
  monitor: (enabled: boolean = true) => {
    if (enabled) {
      console.log('📡 API monitoring enabled');
      // 这里可以添加监控逻辑
    } else {
      console.log('📡 API monitoring disabled');
    }
  },

  // 模拟API延迟
  simulateLatency: (ms: number) => {
    console.log(`⏱️ Simulating ${ms}ms API latency`);
    // 这里可以添加延迟模拟逻辑
  },

  // 模拟API错误
  simulateError: (errorRate: number) => {
    console.log(`💥 Simulating ${errorRate * 100}% API error rate`);
    // 这里可以添加错误模拟逻辑
  },

  // 获取API调用日志
  getLogs: () => {
    console.log('📋 Getting API call logs...');
    // 这里可以返回API调用日志
    return [];
  },
};

// 在开发环境下暴露到全局
if (process.env.NODE_ENV === 'development') {
  (window as any).apiDevTools = apiDevTools;
  (window as any).apiServiceManager = apiServiceManager;
  console.log('🛠️ API dev tools available at window.apiDevTools');
}

// 默认导出
export default {
  apiServiceManager,
  apiUtils,
  apiDevTools,
};
